package com.netty.discovery;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netty.common.constant.Constant;
import com.netty.connect.ConnectManage;

/**
 * 服务发现
 * @author dwjf321
 *
 */
public class ServiceDiscovery {
	
	private static final Logger logger = LoggerFactory.getLogger(ServiceDiscovery.class);
	
	/**
	 * 
	 */
	private CountDownLatch latch = new CountDownLatch(1);
	/**
	 * 服务数据
	 */
	private volatile List<String> dataList = new ArrayList<String>();
	/**
	 * 注册地址
	 */
	private String registryAddress;
	
	private ZooKeeper zk;
	public ServiceDiscovery(String registryAddress){
		this.registryAddress = registryAddress;
		zk = connectServer();
		if (zk != null) {
			watchNode(zk);
		}
	}
	
	private void watchNode(ZooKeeper zk) {
		try {
			List<String> nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
				
				@Override
				public void process(WatchedEvent event) {
					if (event.getType() == Event.EventType.NodeChildrenChanged) {
						watchNode(zk);
					}
				}
			});
			List<String> dataList = new ArrayList<String>();
			for (String node : nodeList) {
				byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH+"/"+node, false, null);
				dataList.add(new String(bytes));
			}
			logger.debug("node data:{}"+dataList);
			this.dataList = dataList;
			updateConnectedServer();
		} catch (KeeperException | InterruptedException e) {
			logger.error("",e);
		}
		
	}

	/**
	 * 更新连接
	 */
	private void updateConnectedServer() {
		ConnectManage.getInstance().updateConnectedServer(dataList);
		
	}

	/**
	 * 连接zk
	 * @return
	 */
	private ZooKeeper connectServer() {
		ZooKeeper zk = null;
		try {
			zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
				
				@Override
				public void process(WatchedEvent event) {
					if (event.getState() == Event.KeeperState.SyncConnected) {
						latch.countDown();
					}
					
				}
			});
			latch.await();
		} catch (Exception e) {
			logger.error("",e);
		}
		return zk;
	}

	/**
	 * 发现服务
	 * @return
	 */
	public String discover() {
		String data = null;
		int size = dataList.size();
		if (size > 0) {
			if (size == 1) {
				data = dataList.get(0);
				logger.debug("using only data: {}", data);
			}else {
				//随机取一个服务
				data = dataList.get(ThreadLocalRandom.current().nextInt(size));
				logger.debug("using random data:{}",data);
			}
		}
		return data;
	}

	/**
	 * 断开zk
	 */
	public void stop() {
		if (zk != null) {
			try {
				zk.close();
			} catch (InterruptedException e) {
				logger.error("",e);
			}
		}
		
	}

}
